﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.Phone.Reactive;
using RssReaderTemplate.Model;
using RssReaderTemplate.Repositories;
using System.Runtime.Serialization;
using System.Collections.Generic;

namespace RssReaderTemplate.ViewModels
{
    [DataContract]
    public class DetailsViewModel : NetworkRequiredViewModel, IObserver<RssItem>
    {
        private IDisposable _subscription;
        public DetailsViewModel(RssRepository repository, Guid id, int index)
        {
            _index = index;
            repository.ObserveOnDispatcher().Subscribe(x =>
            {
                Items.Add(x);
                First = index == 0;
                Last = Index >= Items.Count;
            });
            _subscription = repository.SkipWhile(x => x.Id.CompareTo(id) != 0).Take(1).ObserveOnDispatcher().Subscribe(this);
        }

        private int _index;
        [DataMember]
        public int Index
        {
            get { return _index; }
            set
            {
                _index = value;
                OnPropertyChanged("Index");
            }
        }


        private RssItem _selectedtItem;

        [DataMember]
        public RssItem SelectedItem
        {
            get
            {
                return _selectedtItem;
            }
            set
            {
                _selectedtItem = value;
                OnPropertyChanged("SelectedItem");
            }
        }

        private IList<RssItem> _items = new List<RssItem>();
        [DataMember]
        public IList<RssItem> Items
        {
            get { return _items; }
            set { _items = value; }
        }

        private bool _firs;
        [DataMember]
        public bool First
        {
            get { return _firs; }
            set
            {
                _firs = value;
                OnPropertyChanged("First");
            }
        }

        private bool _last;

        [DataMember]
        public bool Last
        {
            get { return _last; }
            set
            {
                _last = value;
                OnPropertyChanged("Last");
            }
        }



        public void OnCompleted()
        {
            _subscription.Dispose();
            _subscription = null;
        }

        public void OnError(Exception exception)
        {
        }

        public void OnNext(RssItem value)
        {
            SelectedItem = value;
        }
    }
}
